package com.ruoyi.quartz.task;

import com.google.gson.Gson;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.tongban.androidapi.domain.AndroidSendChildSignMessage;
import com.ruoyi.tongban.androidapi.domain.AndroidSocketSession;
import com.ruoyi.tongban.androidapi.util.AndroidSessionCache;
import com.ruoyi.tongban.domain.FacePerson;
import com.ruoyi.tongban.domain.FaceTvDevice;
import com.ruoyi.tongban.service.IFaceTvDeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * @Description
 * @Author caiyanshan
 * @Date 2021/4/24 11:55
 * @Param
 * @Return
 */
@Component("sendChild")
public class sendChildTask {
  
  private static final Logger logger = LoggerFactory.getLogger(sendChildTask.class);
  
  @Autowired
  private RedisCache redis;
  
  @Autowired
  private IFaceTvDeviceService faceTvDeviceService;
  
  public void sendToTv() {
/*    if(true){
      return;
    }*/
    String key = "androidSendChildSignMessage:*";
    Collection<String> itemCollection = redis.keys(key);
    for(String temp : itemCollection){
      AndroidSendChildSignMessage androidSendChildSignMessage = redis.getCacheObject(temp);
      if(androidSendChildSignMessage == null){
        logger.info("not found need send data");
        continue;
      }
      FacePerson facePerson = androidSendChildSignMessage.getFacePerson();
      FaceTvDevice faceTvDevice = new FaceTvDevice();
      faceTvDevice.setTvClassId(facePerson.getClassId());
      faceTvDevice.setTvDeptId(facePerson.getDeptId());
      faceTvDevice.setTvGradeId(facePerson.getGradeId());
      List<FaceTvDevice> faceTvDeviceList = faceTvDeviceService.selectFaceTvDeviceList(faceTvDevice);//班级
      List<FaceTvDevice> tempList = faceTvDeviceService.selectFaceTvDeviceOfDeptId(faceTvDevice);//大厅的(classId为空)
      faceTvDeviceList.addAll(tempList);
      if(faceTvDeviceList.size() == 0){
        logger.info("not found Tv device");
        continue;
      }
      androidSendChildSignMessage.setCmd("sendChildrenSign");
      for(FaceTvDevice tvDevice : faceTvDeviceList){
        String sn = tvDevice.getTvSn();
        androidSendChildSignMessage.setSn(sn);
        Gson gson = new Gson();
        try{
          AndroidSocketSession session = AndroidSessionCache.getSession(sn);
          if(session == null){//设备不在线
            logger.info("tv device no online");
            continue;
          }
          session.getSession().sendText(gson.toJson(androidSendChildSignMessage));
          redis.deleteObject(temp);
          logger.info("send data is success, the sn is : " + sn);
        }catch (Exception e){
          logger.info("" + e);
        }
      }
    }
  }
}
